import { Injectable } from '@nestjs/common';
import { PrismaService } from '@app/prisma';
import { SegmentTextDto } from './dto/segment-text.dto';
import { AddWordRelationDto } from './dto/add-word-relation.dto';
import { SaveTextRecordDto } from './dto/save-text-record.dto';
let nodejieba: any;
try {
  nodejieba = require('nodejieba');
} catch (error) {
  console.warn('nodejieba not available, falling back to simple segmentation');
}

@Injectable()
export class WordService {
  constructor(private readonly prisma: PrismaService) {}

  /**
   * 使用 nodejieba 进行中文分词
   */
  async segmentText(dto: SegmentTextDto) {
    const { text } = dto;
    
    let segments: string[];
    
    if (nodejieba) {
      // 使用 nodejieba 进行分词
      segments = nodejieba.cut(text, true); // true 表示使用 HMM 模式，提高准确性
    } else {
      // 回退到简单分词逻辑
      segments = this.simpleSegmentation(text);
    }
    
    // 过滤空字符串和纯空格
    const filteredSegments = segments.filter(word => word.trim().length > 0);
    
    // 确保所有分词结果在数据库中存在
    for (const word of filteredSegments) {
      await this.ensureWordExists(word);
    }

    return filteredSegments;
  }

  private simpleSegmentation(text: string): string[] {
    // 简单的分词逻辑作为回退方案
    const segments: string[] = [];
    
    // 按空格和标点符号分割
    const basicSegments = text.split(/[\s\p{P}]+/u).filter(s => s.length > 0);
    
    for (const segment of basicSegments) {
      if (/^[\u4e00-\u9fff]+$/.test(segment)) {
        // 中文文本，尝试识别常见词汇模式
        const commonWords = this.extractCommonChineseWords(segment);
        if (commonWords.length > 0) {
          segments.push(...commonWords);
        } else {
          // 如果没有识别到常见词汇，按字符分割
          segments.push(...segment.split(''));
        }
      } else {
        // 非中文文本直接添加
        segments.push(segment);
      }
    }
    
    return segments;
  }

  private extractCommonChineseWords(text: string): string[] {
    const commonWords = [
      '我们', '你们', '他们', '这个', '那个', '什么', '怎么', '为什么', '因为', '所以',
      '但是', '然后', '现在', '以前', '以后', '今天', '明天', '昨天', '时候', '地方',
      '东西', '事情', '问题', '方法', '办法', '意思', '感觉', '想法', '看法', '说法'
    ];
    
    const result: string[] = [];
    let remaining = text;
    
    while (remaining.length > 0) {
      let found = false;
      
      // 从最长的词开始匹配
      for (let len = Math.min(4, remaining.length); len >= 2; len--) {
        const word = remaining.substring(0, len);
        if (commonWords.includes(word)) {
          result.push(word);
          remaining = remaining.substring(len);
          found = true;
          break;
        }
      }
      
      if (!found) {
        result.push(remaining.charAt(0));
        remaining = remaining.substring(1);
      }
    }
    
    return result;
  }

  /**
   * 搜索可替换的词汇
   */
  async searchReplaceableWords(word: string) {
    // 确保当前词汇存在
    await this.ensureWordExists(word);

    const currentWord = await this.prisma.model.word.findUnique({
      where: { text: word },
    });

    if (!currentWord) {
      return [];
    }

    // 查找可替换的词汇（双向关系）
    const relations = await this.prisma.model.wordRelation.findMany({
      where: {
        OR: [
          { sourceWordId: currentWord.id },
          { targetWordId: currentWord.id },
        ],
      },
      include: {
        sourceWord: true,
        targetWord: true,
      },
      orderBy: {
        frequency: 'desc',
      },
    });

    // 提取替换词汇
    const replaceableWords = relations.map(relation => {
      const isSource = relation.sourceWordId === currentWord.id;
      const replaceWord = isSource ? relation.targetWord : relation.sourceWord;
      return {
        word: replaceWord.text,
        frequency: relation.frequency,
      };
    });

    // 去重并返回
    const uniqueWords = Array.from(
      new Map(replaceableWords.map(item => [item.word, item])).values()
    );

    return uniqueWords;
  }

  /**
   * 添加词汇关系
   */
  async addWordRelation(dto: AddWordRelationDto) {
    const { sourceWord, targetWord } = dto;

    // 确保两个词汇都存在
    await this.ensureWordExists(sourceWord);
    await this.ensureWordExists(targetWord);

    const sourceWordRecord = await this.prisma.model.word.findUnique({
      where: { text: sourceWord },
    });

    const targetWordRecord = await this.prisma.model.word.findUnique({
      where: { text: targetWord },
    });

    if (!sourceWordRecord || !targetWordRecord) {
      throw new Error('词汇不存在');
    }

    // 检查关系是否已存在
    const existingRelation = await this.prisma.model.wordRelation.findUnique({
      where: {
        sourceWordId_targetWordId: {
          sourceWordId: sourceWordRecord.id,
          targetWordId: targetWordRecord.id,
        },
      },
    });

    if (existingRelation) {
      // 如果关系已存在，增加使用频率
      await this.prisma.model.wordRelation.update({
        where: { id: existingRelation.id },
        data: { frequency: existingRelation.frequency + 1 },
      });
    } else {
      // 创建新关系
      await this.prisma.model.wordRelation.create({
        data: {
          sourceWordId: sourceWordRecord.id,
          targetWordId: targetWordRecord.id,
          frequency: 1,
        },
      });
    }

    // 创建反向关系（双向绑定）
    const reverseRelation = await this.prisma.model.wordRelation.findUnique({
      where: {
        sourceWordId_targetWordId: {
          sourceWordId: targetWordRecord.id,
          targetWordId: sourceWordRecord.id,
        },
      },
    });

    if (reverseRelation) {
      await this.prisma.model.wordRelation.update({
        where: { id: reverseRelation.id },
        data: { frequency: reverseRelation.frequency + 1 },
      });
    } else {
      await this.prisma.model.wordRelation.create({
        data: {
          sourceWordId: targetWordRecord.id,
          targetWordId: sourceWordRecord.id,
          frequency: 1,
        },
      });
    }

    return { success: true };
  }

  /**
   * 删除词汇关系
   */
  async removeWordRelation(sourceWord: string, targetWord: string) {
    const sourceWordRecord = await this.prisma.model.word.findUnique({
      where: { text: sourceWord },
    });

    const targetWordRecord = await this.prisma.model.word.findUnique({
      where: { text: targetWord },
    });

    if (!sourceWordRecord || !targetWordRecord) {
      throw new Error('词汇不存在');
    }

    // 删除双向关系
    await this.prisma.model.wordRelation.deleteMany({
      where: {
        OR: [
          {
            sourceWordId: sourceWordRecord.id,
            targetWordId: targetWordRecord.id,
          },
          {
            sourceWordId: targetWordRecord.id,
            targetWordId: sourceWordRecord.id,
          },
        ],
      },
    });

    return { success: true };
  }

  /**
   * 保存文本记录
   */
  async saveTextRecord(dto: SaveTextRecordDto) {
    const { originalText, segmentedWords, replacedText, replacements } = dto;

    const record = await this.prisma.model.textRecord.create({
      data: {
        originalText,
        segmentedText: JSON.stringify(segmentedWords),
        replacedText,
        replacements: replacements ? JSON.stringify(replacements) : null,
      },
    });

    return record;
  }

  /**
   * 获取文本记录历史
   */
  async getTextRecords(page = 1, limit = 10) {
    const skip = (page - 1) * limit;

    const [records, total] = await Promise.all([
      this.prisma.model.textRecord.findMany({
        skip,
        take: limit,
        orderBy: { createdAt: 'desc' },
      }),
      this.prisma.model.textRecord.count(),
    ]);

    return {
      records: records.map(record => ({
        ...record,
        segmentedText: JSON.parse(record.segmentedText),
        replacements: record.replacements ? JSON.parse(record.replacements) : null,
      })),
      total,
      page,
      limit,
      totalPages: Math.ceil(total / limit),
    };
  }

  /**
   * 确保词汇存在于数据库中
   */
  private async ensureWordExists(text: string) {
    const existingWord = await this.prisma.model.word.findUnique({
      where: { text },
    });

    if (!existingWord) {
      await this.prisma.model.word.create({
        data: { text },
      });
    }
  }
}